import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Radio,
  Form,
  Icon,
  Upload,
  message,
  Input,
  Modal,
  Select,
  Button,
  Table,
  DatePicker,
} from 'antd';
import moment from 'moment';
import styles from './LeaderServing.less';

const Option = Select.Option;
const { TextArea } = Input;
const RadioGroup = Radio.Group;


function beforeUpload(file) {
  console.log(file);
  const JPGoPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!JPGoPNG) {
    message.error('仅支持JPG或PNG格式图片!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('限制大小2MB以内!');
  }
  return JPGoPNG && isLt2M;
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

@connect(({ LeaderServing }) => ({
  leaderServingData: LeaderServing.leaderServingData,
  updateDidFinish: LeaderServing.updateDidFinish,
}))
class LeaderServing extends Component {
  state = {
    user_name: '',
    page_num: 1,
    type: 0,
    modalVisibility: false,
    selectedRows: [],
    modalId: undefined,
    modalReportType: 1,
    modalPublishState: 0,
    modalPublishDate: undefined,
    modalOperation: 'new',
    imageUrl:'',
    loading:false,
    user_name:'',
    head_photo_url:'',
    english_user_name:'',
    gender:0,
    birthday:'',
    position_name:'',
    phone_number:'',
    fax:'',
    telephone:'',
    email:'',
    nationality:0,
    certificate_type:0,
    certificate_number:'',
    post_code:'',
    address:'',
    resume:'',
    note:''

  };

  updateData() {
    const { dispatch } = this.props;
    dispatch({
      type: 'LeaderServing/queryLeaderServingList',
      payload: {
        page_num: this.state.page_num,
        page_size: 10,
        user_name: this.state.user_name,
      },
    });
  }  

  componentDidMount() {
    this.setState({ loading: false });
    this.updateData();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.updateDidFinish !== this.props.updateDidFinish) {
      this.updateData();
    } else if (prevProps.leaderServingData !== this.props.leaderServingData) {
      this.setState({ selectedRows: [] });
    }
  }

  ToggLoad() {
    console.log(1);
  }

  render() {
    let { leaderServingData } = this.props;

    const cols = [
      {
        title: '姓名',
        dataIndex: 'user_name',
        key: 'user_name',
      },
      {
        title: '性别',
        dataIndex: 'gender',
        key: 'gender',
      },
      {
        title: '证件类型',
        dataIndex: 'certificate_type',
        key: 'certificate_type',
      },
      {
        title: '证件号',
        dataIndex: 'certificate_number',
        key: 'certificate_number',
      },
      {
        title: '固定电话',
        dataIndex: 'telephone',
        key: 'telephone',
      },
      {
        title: '电话',
        dataIndex: 'phone_number',
        key: 'phone_number',
      },
      {
        title: '电子邮箱',
        dataIndex: 'email',
        key: 'email',
      },
      {
        title: '操作',
        key: 'operations',
        dataIndex: 'id',
        render: (text, row, index) => (
          <a
            onClick={() => {
              handleEditClick(index);
            }}
          >
            编辑
          </a>
        ),
      },
    ];

    let pager = {
      defaultCurrent: 1,
      total: leaderServingData.total_count,
      onChange: (page, pageSize) => {
        this.setState({ page_num: page }, () => {
          this.updateData();
          this.setState({ selectedRows: [] });
        });
      },
    };

    let handleEditClick = index => {
      this.setState({
        modalId: leaderServingData.data_list[index].id,
        modalReportType: typeMap[leaderServingData.data_list[index].report_type],
        modalPublishState: stateMap[leaderServingData.data_list[index].published_state],
        modalPublishDate: leaderServingData.data_list[index].published_time,
        modalVisibility: true,
        modalOperation: 'update',
      });
    };

    let handleChange = (info)=>{
      let that = this;
      if (info.file.status === 'uploading') {
        that.setState({ loading: true });
        return;
      }
      if (info.file.status === 'done') {
        that.setState({head_photo_url:info.file.response.data.img_url})
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl =>
          that.setState({
            imageUrl,
            loading: false,
          })
        );
      }
    };
    let handleDeleteClick = () => {
      if (this.state.selectedRows.length > 0) {
        const { dispatch } = this.props;
        let res = [];
        for (let i = 0; i < this.state.selectedRows.length; i++) {
          res.push(leaderServingData.data_list[this.state.selectedRows[i]].id);
        }
        dispatch({
          type: 'LeaderServing/deleteSensitiveWindow',
          payload: {
            id: res.join(','),
          },
        });
      }
    };

    let handleTypeChange = type => {
      this.setState({ type });
    };

    let handleTableSelectChange = selectedRows => {
      console.log(selectedRows);
      this.setState({ selectedRows });
    };

    let clearModalValues = () => {
      this.setState({
        imageUrl:'',
        user_name:'',
        head_photo_url:'',
        english_user_name:'',
        gender:0,
        birthday:'',
        position_name:'',
        phone_number:'',
        fax:'',
        telephone:'',
        email:'',
        nationality:0,
        certificate_type:0,
        certificate_number:'',
        post_code:'',
        address:'',
        resume:'',
        note:''
      });
    };

    let handleModalOk = e => {
      console.log(this);
      if(!this.state.head_photo_url.length||!this.state.birthday.length||!this.state.user_name.length){
          Modal.error({
            title: '请确认信息填写完整',
            content: '带星号信息为必填，请确认填写无误后再次提交！',
          });
      }
      else {
        const { dispatch } = this.props;
        if (this.state.modalOperation === 'new') {
          dispatch({
            type: 'LeaderServing/addManageData',
            payload: {
              user_name: this.state.user_name,
              head_photo_url: this.state.head_photo_url,
              english_user_name: this.state.english_user_name,
              gender: this.state.gender,
              birthday: this.state.birthday,
              position_name: this.state.position_name,
              phone_number: this.state.phone_number,
              fax: this.state.fax,
              telephone: this.state.telephone,
              email: this.state.email,
              nationality: this.state.nationality,
              certificate_type: this.state.certificate_type,
              certificate_number: this.state.certificate_number,
              post_code: this.state.post_code,
              address: this.state.address,
              resume: this.state.resume,
              note: this.state.note
            }
          });
        } else {
          dispatch({
            type: 'LeaderServing/updateManageData',
            payload: {
              user_name: this.state.user_name,
              head_photo_url: this.state.head_photo_url,
              english_user_name: this.state.english_user_name,
              gender: this.state.gender,
              birthday: this.state.birthday,
              position_name: this.state.position_name,
              phone_number: this.state.phone_number,
              fax: this.state.fax,
              telephone: this.state.telephone,
              email: this.state.email,
              nationality: this.state.nationality,
              certificate_type: this.state.certificate_type,
              certificate_number: this.state.certificate_number,
              post_code: this.state.post_code,
              address: this.state.address,
              resume: this.state.resume,
              note: this.state.note
            }
          });
        }
        clearModalValues();
      }
      
    };

    let handleModalCancel = e => {
      clearModalValues();
    };

    let handleModalTypeChange = modalReportType => {
      this.setState({ modalReportType });
    };

    let handleModalStateChange = modalPublishState => {
      this.setState({ modalPublishState });
    };

    let handleModalDateChange = (moment, modalPublishDate) => {
      this.setState({ birthday:modalPublishDate });
    };

    let onChangeUserName = (e) => {
      this.setState({ user_name: e.target.value });
    }

    let onChangeEngName = (e) => {
      this.setState({ english_user_name: e.target.value });
    }

    let onChangeGender= (e)=>{
      this.setState({ gender: e.target.value });
    }

    let onChangePosName = (e) => {
      this.setState({ position_name: e.target.value });
    }

    let onChangePhoneNumber = (e) => {
      this.setState({ phone_number: e.target.value });
    }

    let onChangeFax = (e) => {
      this.setState({ fax: e.target.value });
    }

    let onChangeTel = (e) => {
      this.setState({ telephone: e.target.value });
    }

    let onChangeEMail = (e) => {
      this.setState({ email: e.target.value });
    }

    let onChangeNation = (value) => {
      this.setState({ email:value });
    }

    let onChangeCertify = (value) => {
      this.setState({ certificate_type:value });
    }

    let onChangeCertifyId = (e) => {
      this.setState({ certificate_number: e.target.value });
    }

    let onChangePostCode = (e) => {
      this.setState({ post_code: e.target.value });
    }

    let onChangeAddress = (e) => {
      this.setState({ address: e.target.value });
    }

    let onChangeResume = (e) => {
      this.setState({ resume: e.target.value });
    }

    let onChangeNote = (e) => {
      this.setState({ note: e.target.value });
    }

    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    const imageUrl = this.state.imageUrl;

    return (
      <div style={{ margin: '24px 24px 0' }}>
        <div className={styles.outerWidthLim}>
          <div className={styles.outerHeightLim}>
            <div className={styles.contentCard}>
              <div className={styles.cardHeader}>
                <p className={styles.cardTitle}>董监高任职</p>
                <div className={styles.operationBox}>
                  <a
                    onClick={() => {
                      this.setState({ modalVisibility: true, modalOperation: 'new' });
                    }}
                  >
                    添加
                  </a>
                  <span className={styles.smallGap}>|</span>
                  <a onClick={handleDeleteClick}>删除</a>
                  <span className={styles.smallGap}>|</span>
                  <a>下载模板</a>
                  <span className={styles.smallGap}>|</span>
                  <a>人员导入</a>
                  <span className={styles.smallGap}>|</span>
                  <a>人员导出</a>
                </div>
                <Modal
                  title="添加董监高任职"
                  okText="保存"
                  visible={this.state.modalVisibility}
                  onOk={handleModalOk}
                  width="850px"
                  onCancel={handleModalCancel}
                  maskClosable={false}
                >
                  <div className={styles.modalWrap}>
                    <div className={styles.modalCol}>
                      <div className={[styles.uploadWrap, styles.inputWrapper].join(' ')}>
                        <span className={[styles.SelectTitle, styles.mustTitle].join(' ')}>
                          上传头像:
                        </span>
                        <Upload
                          name="file"
                          listType="picture-card"
                          className="avatar-uploader"
                          showUploadList={false}
                          action="http://101.200.59.101/gold/file_upload"
                          beforeUpload={beforeUpload}
                          onChange={handleChange}
                        >
                          {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
                        </Upload>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={[styles.SelectTitle, styles.mustTitle].join(' ')}>
                          姓名:
                        </span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeUserName}/>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>外文名:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeEngName}/>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={[styles.SelectTitle, styles.mustTitle].join(' ')}>
                          性别:
                        </span>
                        <RadioGroup onChange={onChangeGender} value={this.state.gender}>
                          <Radio value={0}>男</Radio>
                          <Radio value={1}>女</Radio>
                        </RadioGroup>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>出生年月：</span>
                        <DatePicker
                          className={styles.inputCell}
                          defaultValue={
                            this.state.modalPublishDate
                              ? moment(this.state.modalPublishDate, 'YYYY-MM-DD')
                              : moment()
                          }
                          onChange={handleModalDateChange}
                        />
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>称谓:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangePosName}/>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>移动电话:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangePhoneNumber}/>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>传真:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeFax}/>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>固定电话:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeTel}/>
                      </div>
                    </div>

                    <div className={styles.modalCol}>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>电子邮箱:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeEMail}/>
                      </div>
                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>请选择国籍:</span>
                        <Select defaultValue="0" className={styles.inputCell} onChange={onChangeNation}>
                          <Option value="0">请选择国籍</Option>
                          <Option value="1">中国</Option>
                          <Option value="2">中国香港</Option>
                          <Option value="3">中国台湾</Option>
                          <Option value="4">中国澳门</Option>
                          <Option value="5">其他国家</Option>
                        </Select>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>证件类型:</span>
                        <Select defaultValue="0" className={styles.inputCell} onChange={onChangeCertify}>
                          <Option value="0">请选择证件类型</Option>
                          <Option value="1">境内身份证</Option>
                          <Option value="2">军官证</Option>
                          <Option value="3">士兵证</Option>
                          <Option value="4">境外身份证</Option>
                          <Option value="5">组织机构代码证件</Option>
                          <Option value="5">其他</Option>
                        </Select>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>证件号:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeCertifyId}/>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>邮编:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangePostCode}/>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>地址:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeAddress}/>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>简历:</span>
                        <TextArea className={styles.inputCell} onChange={onChangeResume}/>
                      </div>

                      <div className={styles.inputWrapper}>
                        <span className={styles.SelectTitle}>备注:</span>
                        <Input className={styles.inputCell} type="text" onChange={onChangeNote}/>
                      </div>
                    </div>
                  </div>
                </Modal>
              </div>
              <div className={styles.cardContent}>
                <div>
                  <span>姓名</span>
                  <Input placeholder="姓名" style={{ width: '200px', marginLeft: '20px' }} />

                  <Button
                    type="primary"
                    className={styles.tableButton + ' ' + styles.pullRight}
                    onClick={() => {
                      this.updateData();
                    }}
                  >
                    查询
                  </Button>
                </div>
                <Table
                  className={styles.bigTable}
                  columns={cols}
                  rowSelection={{
                    selectedRowKeys: this.state.selectedRows,
                    onChange: handleTableSelectChange,
                  }}
                  dataSource={leaderServingData.data_list}
                  pagination={pager}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default LeaderServing;
